package com.act.moudles.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.act.components.UserComponent;
import com.act.constant.LoginTypeEnums;
import com.act.moudles.user.entity.User;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.act.moudles.user.dao.SecretKeyDao;
import com.act.moudles.user.entity.SecretKey;
import com.act.moudles.user.service.SecretKeyService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * 密钥(SecretKey)表服务实现类
 *
 * @author makejava
 * @since 2023-05-18 11:09:01
 */
@Service("secretKeyService")
public class SecretKeyServiceImpl extends ServiceImpl<SecretKeyDao, SecretKey> implements SecretKeyService {

    @Resource
    private UserComponent userComponent;

    @Resource
    private SecretKeyDao secretKeyDao;

    @Override
    public String genSecretValue() {
        //1.查询当前人员
        User user = userComponent.getCurrentUser(LoginTypeEnums.WEB.getType());
        if(user == null){
            return null;
        }
        //2.密钥生成基础
        String baseStr = user.getUserId() +user.getUserType()+ userComponent.getUserTenAntId() + System.currentTimeMillis() +"";
        return DigestUtils.md5DigestAsHex(baseStr.getBytes()  ).toLowerCase();
    }


    @Override
    public String findSaTokenBySecretValue(String secret,String userName,String pwd) throws Exception {
        //1.根据登录名查询用户
        User user = userComponent.getUserByLoginName(userName);
        if(user == null){
            throw new RuntimeException("用户名(userName)不存在："+userName);
        }
        if(!user.getPassword().equals(pwd)){
            throw new RuntimeException("用户密码(pwd)不正确："+pwd);
        }

        //2.查询密钥
        SecretKey secretKey = secretKeyDao.selectByValue(secret,user.getUserId());
        if(secretKey == null){
            throw  new RuntimeException("密钥(secret)不存在:"+secret);
        }
        if(secretKey.getOutTime().getTime() - System.currentTimeMillis() < 0L){
            throw  new RuntimeException("密钥(secret)已过期，过期时间:"+ DateFormatUtils.format(secretKey.getOutTime(),"yyyy.MM.dd HH:mm:ss"));
        }

        //2.登录
        StpUtil.login(user.getUserId(),LoginTypeEnums.SECRET.getType());
        userComponent.setUserBasicSession(user,LoginTypeEnums.SECRET.getType());
        return StpUtil.getTokenValue();
    }

    @Override
    public IPage<SecretKey> pageKey(Page<SecretKey> page, SecretKey secretKey) {
        IPage<SecretKey>  retPage = page(page,secretKey.query());
        List<SecretKey> list = retPage.getRecords();
        List<Long>  userIds = list.stream().map(SecretKey::getCreateUserId).collect(Collectors.toList());
        Map<Long,String> userNameMap = userComponent.getUserName(userIds);
        list.forEach(o->{
            o.setCreateUserName(userNameMap.get(o.getCreateUserId()));
        });
        retPage.setRecords(list);
        return retPage;
    }

    @Override
    public Boolean addKey(SecretKey secretKey) {
        secretKey.setCreateUserId(userComponent.getUserId(LoginTypeEnums.WEB.getType()));
        secretKey.setTenantId(userComponent.getUserTenAntId());
        secretKey.setCreateTime(new Date());
        secretKey.setOutTime(DateUtils.addYears(secretKey.getCreateTime(),1));
        return save(secretKey);
    }

    @Override
    public Boolean updateKey(SecretKey secretKey) {
        secretKey.setCreateUserId(userComponent.getUserId(LoginTypeEnums.WEB.getType()));
        return updateById(secretKey);
    }

    @Override
    public Boolean removeKey(Long keyId) {
        return removeById(keyId);
    }

    @Override
    public User findUserBySecretKey(String secretkey) {
        SecretKey key =  secretKeyDao.selectByKey(secretkey);
        if(key == null){return null;}
        return userComponent.getUserById(key.getCreateUserId());
    }
}

